package com.winter.controller;

import com.winter.annotation.BaffleAn;
import com.winter.model.User;
import com.winter.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.SecureRandom;

@Controller
@RequestMapping("/")
public class LoginController {

    @Autowired
    private com.winter.service.UserService userService;

    @PostMapping("/register")
    public String register(String userName,String password){
        ByteSource bytes = ByteSource.Util.bytes(userName);
        Object result = new SimpleHash("MD5",password,bytes,1024);
        User user = new User();
        user.setUserName(userName);
        user.setPassword(result.toString());
        user.setSalt("123");

        userService.save(user);
        return "redirect:/login.jsp";
    }


    @PostMapping(value = "/login")
    public String login(String userName,String password){
        UsernamePasswordToken token = new UsernamePasswordToken(userName,password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return "redirect:/index.jsp";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        }
        return "redirect:/login.jsp";
    }

    @RequestMapping("/test")
    @BaffleAn
    public String login1(HttpServletRequest request, HttpServletResponse response){

        System.out.println(request.getParameter("id"));

        return "用户未登录";
    }

    @RequestMapping("/logout")
    public String logout(){
        SecurityUtils.getSubject().logout();

        return "redirect:/login.jsp";
    }
}
